﻿#region Usings

using System;
using System.Security.Cryptography;
using System.Text;

#endregion

namespace Kazkommertsbank.Framework.Common
{
    public static class Utils
    {
        public static bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct
        {
            if(!typeof(T).IsEnum)
                throw new ArgumentException("Type parameter must be an enum");
            var names = Enum.GetNames(typeof(T));
            value = ((T[])Enum.GetValues(typeof(T)))[0];
            foreach(var name in names)
            {
                if(String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
                {
                    value = (T)Enum.Parse(typeof(T), name);
                    return true;
                }
            }
            return false;
        }

        public static void ArgumentNotNull(object argument, string argumentName)
        {
            if(argument == null)
                throw new ArgumentNullException(argumentName);
        }

        public static string StringToBase64(string str)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
        }

        public static string StringFromBase64(string str)
        {
            return Encoding.UTF8.GetString(Convert.FromBase64String(str));
        }

        public static string CreateSignature(string xml, string merchantSig)
        {
            return Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(string.Format("{0}{1}{0}", merchantSig, xml))));
        }

        public static byte[] ConvertStringToByteArray(string s)
        {
            return (new ASCIIEncoding()).GetBytes(s);
        }
    }
}